package org.example.service.impl;

import org.example.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author shenguangyang
 */
@Service
public class MailServiceImpl implements MailService {
    private static final Logger log = LoggerFactory.getLogger(MailServiceImpl.class);
    @Resource
    private JavaMailSender mailSender;

    @Resource
    private MailProperties mailProperties;

    @Resource
    TemplateEngine templateEngine;

    @Override
    public boolean sendVerifyCode(String toAddress, String subject, String operateDescribe, String verifyCode) {
        String fromAddress = mailProperties.getUsername();
        //创建邮件正文
        Context context = new Context();
        context.setVariable("verifyCode", verifyCode);
        context.setVariable("operateDescribe", operateDescribe);
        //将模块引擎内容解析成html字符串
        String emailContent = templateEngine.process("VerifyCodeTemplate", context);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(fromAddress);
            helper.setTo(toAddress);
            helper.setSubject(subject);
            helper.setText(emailContent, true);
            mailSender.send(message);
            return true;
        } catch (MessagingException e) {
            log.error("send mail to [{}] fail, error: {}", toAddress, e.getMessage());
            return false;
        }
    }
}
